package com.springboot.controller;

import java.io.*;
import java.text.DecimalFormat;
import java.text.Format;
import java.util.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ArrayUtil;
import com.springboot.biz.PipeBiz;
import com.springboot.entity.Pipe;
import org.apache.commons.compress.utils.Lists;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.ResourceUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.springboot.biz.ManholeBiz;
import com.springboot.biz.ProjectBiz;
import com.springboot.entity.Manhole;
import com.springboot.entity.Project;
import com.springboot.util.AppUtils;
import com.springboot.util.PDFHelper;
import com.springboot.util.ZipFileHelper;

@RestController
public class DownFileController {

    @Value("${myfile}")
    private String myfile;

    @Resource
    private PDFHelper pdfHelper;
    @Resource
    private ProjectBiz projectBiz;
    @Resource
    private ManholeBiz manholeBiz;
    @Resource
    private PipeBiz pipeBiz;

    @RequestMapping(value = "/project/downfile")
    public void downProject(@RequestParam(defaultValue = "0") int id) {
        Project project = projectBiz.findInfoProject(id, null);
        if (StringUtils.isEmpty(project))
            return; // 查询项目为空
        String name = AppUtils.UUIDCode();
        String srcPath = myfile + "/report/";
        String zipPath = myfile + "/compre/";
        File srcFile = new File(srcPath + name + "/");
        srcFile.mkdirs();
        Format format = new DecimalFormat("#00");
        List<Manhole> manholes = manholeBiz.findListManhole(project);
        for (Manhole manhole : manholes)
            pdfHelper.initPDF(manhole, srcFile.getPath(), manhole.getDrainage());

        HttpServletResponse response = AppUtils.getResponse();
        String fileName = project.getDate() + "_" + project.getName();
        File zipFile = ZipFileHelper.toZip(srcPath + name, zipPath, fileName);
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".zip");
        response.setContentType("application/octet-stream");
        try {
            int len = -1;
            byte[] buffer = new byte[1024];
            InputStream fstream = new FileInputStream(zipFile.getPath());
            InputStream bstream = new BufferedInputStream(fstream);
            OutputStream outputStream = response.getOutputStream();
            while ((len = bstream.read(buffer)) > 0) {
                outputStream.write(buffer, 0, len);
                outputStream.flush();
            }
            bstream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        for (File file : Objects.requireNonNull(srcFile.listFiles()))
            file.delete();
        srcFile.delete();
        zipFile.delete();
    }

    @RequestMapping(value = "/manhole/downfile")
    public void downManhole(@RequestParam(defaultValue = "0") int id) {
        Manhole manhole = manholeBiz.findInfoManhole(id, null);
        if (StringUtils.isEmpty(manhole))
            return; // 查询项目为空
        String name = AppUtils.UUIDCode();
        String srcPath = myfile + "/report/";
        File srcFile = new File(srcPath + name + "/");
        srcFile.mkdirs();

        pdfHelper.initPDF(manhole, srcFile.getPath(), "01");
        HttpServletResponse response = AppUtils.getResponse();
        File zipFile = new File(srcFile.getPath() + "/" + "01.pdf");
        response.setHeader("Content-disposition", "attachment;filename=" + manhole.getDrainage() + ".pdf");
        response.setContentType("application/octet-stream");
        try {
            int len = -1;
            byte[] buffer = new byte[1024];
            InputStream fstream = new FileInputStream(zipFile.getPath());
            InputStream bstream = new BufferedInputStream(fstream);
            OutputStream outputStream = response.getOutputStream();
            while ((len = bstream.read(buffer)) > 0) {
                outputStream.write(buffer, 0, len);
                outputStream.flush();
            }
            bstream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        zipFile.delete();
        srcFile.delete();
    }


    @RequestMapping(value = "/exportfile")
    public void exportFile(HttpServletResponse response, @RequestParam(defaultValue = "") int id) {
        try {
            Project project = projectBiz.findInfoProject(id, null);
            if (StringUtils.isEmpty(project))
                return; // 查询项目为空
            List<Manhole> manholes = manholeBiz.findListManhole(project);
            for (Manhole manhole : manholes) {
                manhole.setInspection("I");
                if (Objects.equals("Y", manhole.getUtil1()))
                    manhole.setInspection("C");
                if (Objects.equals("Y", manhole.getUtil2()))
                    manhole.setInspection("M");
                if (Objects.equals("Y", manhole.getUtil3()))
                    manhole.setInspection("P");
                if (Objects.equals("Y", manhole.getUtil4()))
                    manhole.setInspection("I");

                Map<String, String> pipeSize = new HashMap<>();
                List<Pipe> pipes = pipeBiz.findListPipe(manhole);
                pipeSize.put("size1", Convert.toStr(pipes.get(0).getSize1(), ""));
                pipeSize.put("size2", Convert.toStr(pipes.get(1).getSize1(), ""));
                pipeSize.put("size3", Convert.toStr(pipes.get(2).getSize1(), ""));
                pipeSize.put("size4", Convert.toStr(pipes.get(3).getSize1(), ""));
                pipeSize.put("size8", Convert.toStr(pipes.get(8).getSize1(), ""));
                pipeSize.put("size9", Convert.toStr(pipes.get(9).getSize1(), ""));
                manhole.setPipeSize(pipeSize);

                manhole.setCoverSize(manhole.getCover1() + " * " + manhole.getCover2());
                if (Objects.equals(manhole.getCover1(), "450") && Objects.equals(manhole.getCover2(), "450"))
                    manhole.setCoverSize("A");
                if (Objects.equals(manhole.getCover1(), "570") && Objects.equals(manhole.getCover2(), "570"))
                    manhole.setCoverSize("B");
                if (Objects.equals(manhole.getCover1(), "675") && Objects.equals(manhole.getCover2(), "675"))
                    manhole.setCoverSize("C");
                if (Objects.equals(manhole.getCover1(), "745") && Objects.equals(manhole.getCover2(), "895"))
                    manhole.setCoverSize("D");
            }

            Map<String, Object> map = new HashMap<>(manholes.size());
            map.put("manholes", manholes);

            File pipeTemp = ResourceUtils.getFile("classpath:pipeTemp.xlsx");
            TemplateExportParams params = new TemplateExportParams(pipeTemp.getPath(), true);
            params.setSheetName(new String[]{"Manhole Inspection"});
            Workbook workbook = ExcelExportUtil.exportExcel(params, map);

            response.setHeader("Content-disposition", "attachment;filename=" + project.getName() + ".xlsx");
            response.setContentType("application/octet-stream");
            workbook.write(response.getOutputStream());
            response.flushBuffer();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
